import { useWsStore } from '@/stores/module/ws'
import { useLoginStore } from '@/stores/module/login'
import { useUserStore } from '@/stores/module/user'
import storage from '@/storage'
import { message } from 'ant-design-vue'
import { useUserInfoStore } from '@/stores/module/user/userInfo'
// import { MesConnect } from './wsMes'
const wsStore = useWsStore()
const loginStore = useLoginStore()
const userStore = useUserStore()
const userInfoStore = useUserInfoStore()
//登录验证ws
export function wsLogin() {
  //非空类型判断
  if (wsStore.wsInstance == null) return
  if (!loginStore.qrUrl) {
    wsStore.wsInstance.send(JSON.stringify({ type: 1 }))
  }
  //扫码状态判断
  wsStore.wsInstance.onmessage = (event) => {
    const wsMessage = JSON.parse(event.data)
    console.log(wsMessage.data);

    if (wsMessage.type == 1) {
      userStore.loginState = wsMessage.type
      loginStore.qrUrl = wsMessage.data.loginUrl
    }
    if (wsMessage.type == 2) {
      userStore.loginState = wsMessage.type
    }
    if (wsMessage.type == 3) {
      userStore.loginState = wsMessage.type
      userStore.userInfo = wsMessage.data
      storage.set('token', wsMessage.data.token)
      loginLogic()
      userInfoStore.getUserInfo()
      // MesConnect()
    }
  }

  wsStore.wsInstance.onerror = (err) => {
    console.error('WebSocket 发生错误:', err)
  }
}
//登录成功部分逻辑抽取
const loginLogic = () => {
  loginStore.openLogin = false
  userStore.isLoginState = true
  message.success('登录成功!')
}

//退出登录
export function wsLogout() {
  if (wsStore.wsInstance == null) return
  wsStore.wsInstance.send(JSON.stringify({ type: 3 }))
}
